import sqlite3
import uuid


conn = sqlite3.connect('kb_sys.db',check_same_thread=False)
#判断特征名称是否存在
def is_contain_feature(_name):
    _cursor=conn.cursor()
    result=_cursor.execute("select * from tb_feature where name=?",(_name,)).fetchall()
    if len(result)>0:
        return True
    else:
        return False

def get_feature(_name):
    _cursor=conn.cursor()
    if len(_name)>0:
        result=_cursor.execute("select * from tb_feature where name=?",(_name,)).fetchall()
    else:
        result=_cursor.execute("select * from tb_feature ").fetchall()
    rtn_dict=[]
    if len(result)>0 :
        for row in result:
            _dict={
                'id':row[0],
                'name':row[1],
                'remark':row[2],
                'is_pstv':row[3]
            }
            rtn_dict.append(_dict)
    return rtn_dict
    

#新建特征
def add_feature(_name,_is_pstv):
    _cursor=conn.cursor()
    _uuid=uuid.uuid4()
    print(_uuid)
    sql="INSERT INTO tb_feature (`id`, `name`, `is_pstv`) VALUES (?,?, ?)"
    result=_cursor.execute(sql,(str(_uuid),_name,_is_pstv,))
    conn.commit()

#新增规则与特征关系
def add_relation(rule_id,ft_id):
    _cursor=conn.cursor()
    sql="INSERT INTO tb_rlt (`rule_id`, `ft_id`) VALUES ( ?, ?)"
    result=_cursor.execute(sql,(rule_id,ft_id,))
    conn.commit()

#根据rule_id获取规则对应的推理前提条件
def get_relations(rule_id):
    sql="SELECT tf.id,tf.name,tf.is_pstv from tb_rlt rlt,tb_feature tf \
    where  tf.id=rlt.ft_id and rule_id=?"
    _cursor=conn.cursor()
    result=_cursor.execute(sql,(rule_id,)).fetchall()
    rtn_dist=[]
    for row in result:
        _dict={
            'cond_id':row[0],
            'cond_name':row[1],
            'cond_type':row[2]
        }
        rtn_dist.append(_dict)
    return rtn_dist


#新增规则
def add_db_rule(ft_id,is_temp):
    _cursor=conn.cursor()
    _uuid=uuid.uuid4();
    _uuid=str(_uuid)
    sql="INSERT INTO `tb_rules` ( `id`,`ft_id`, `is_temp`) VALUES ( ?,?, ?)"
    result=_cursor.execute(sql,(_uuid,ft_id,is_temp,))
    conn.commit()
    return _uuid;

#新增规则落库
def add_rules(ft_names,ccld_name,is_temp):
    #获取同名称结论数据
    rslt=get_feature(ccld_name)
    if len(rslt)<1 :
        add_feature(ccld_name,0)
        rslt=get_feature(ccld_name)
    #结论的ID
    ccld_id=rslt[0]['id']
    rule_id=add_db_rule(ccld_id,is_temp)
    #ule_id=get_rule_id(ccld_id)
    #添加映射关系
    for ft_name in ft_names:
        rslt=get_feature(ft_name)
        if len(rslt)>0 :
            print(rslt)
        else:
            add_feature(ft_name,1)
            rslt=get_feature(ft_name)
        ft_id=rslt[0]['id']
        add_relation(rule_id,ft_id)
    

def get_rule_id(ft_id):
    sql="SELECT id from tb_rules where ft_id=?"
    _cursor=conn.cursor()
    result=_cursor.execute(sql,(ft_id,)).fetchall()
    return result[0][0]

#获取库中所有规则
def get_rules_all():
    sql="select trs.id,is_temp,is_use,name,tf.is_pstv,ft_id from tb_rules trs ,tb_feature tf where trs.ft_id=tf.id"
    _cursor=conn.cursor()
    result=_cursor.execute(sql).fetchall()
    rtn_dict=[]
    for row in result:
        _dict={
            'id':row[0],
            'is_temp':row[1],
            'is_use':row[2],
            'name':row[3],
            'result':row[3],
            'is_pstv':row[4],
            'ft_id':row[5]
        }
        
        _dict['conditions']=get_relations(row[0])
        rtn_dict.append(_dict)
    return rtn_dict

def get_rules_detail():
    data_dict=get_rules_all()
    print(data_dict)
    index=1
    for item in data_dict:
        rlt_dict=get_relations(item['id'])
        conds=[]
        for rltd in rlt_dict:
            cond_type=rltd['cond_type']
            if cond_type==0 :
                conds.append('Result('+rltd['cond_name']+')')
            elif cond_type==2:
                conds.append('Type('+rltd['cond_name']+')')
            else :
                conds.append('Fact('+rltd['cond_name']+')')
        item['conds']=' ^ '.join(conds)
        item['rule_id']='R'+str(index)+':'
        if item['is_temp']==1:
            item['is_temp_desc']='否'
        else:
            item['is_temp_desc']='是'
        is_pstv=item['is_pstv']
        if is_pstv==0:
            item['result']='Result('+item['result']+')'
        elif is_pstv==2:
            item['result']='Type('+item['result']+')'
        else:
            item['result']='Fact('+item['result']+')'

        index+=1
    rtn_dict={
        'code':0,
        'count':len(data_dict),
        'data':data_dict
    }
    return rtn_dict